package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class CheckPermissionInterceptor implements HandlerInterceptor {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IPermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取当前登陆的用户
      //  Employee employee = (Employee) request.getSession().getAttribute("EMPLOYEE_IN_SESSION");
        Employee employee = UserContext.getCurrentUser();
        //2.判断是否超级管理
        if (employee.isAdmin()) {
            //是= >放行
            return true;
        }
        //不是=>3
        //3.获取目标方法
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //拦截器preHandle的第三个参数就是当前被拦截的处理方法
        //4.判断是否有贴注解
        RequiredPermission methodAnnotation = handlerMethod.getMethodAnnotation(RequiredPermission.class);
        //没= >放行
        if (methodAnnotation == null) {
            return true;
        }
        //有=>5
        //5获取用户拥有的权限表达式列表
        String expression = methodAnnotation.expression();
        //6.从注解上获取当前目标方法对应的权限表达式
        List<String> permissions = permissionService.selectByEmpId(employee.getId());
        //7.判断该表达式是否存在用户列表中
        if (permissions.contains(expression)) {
            //是= >放行
            return true;
            //否=>返回错误页面,不放行

        }
        //判断前端是否AJAX请求,如果是就返回json数据
        if(handlerMethod.hasMethodAnnotation(ResponseBody.class)){
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(JSON.toJSONString(new JsonResult(false,"你没有访问权限")));
        }
        else {
            request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp").forward(request, response);
        }
        return false;
    }
}
